

'''
在线词典的客户端
'''

import socket
from getpass import getpass

# 连接服务器
# 1. 定义远程主机的IP
# HOST = '150.158.212.125'
HOST = '127.0.0.1'
# 2. 定义远程主机的端口好
PORT = 5000
ADDR = (HOST, PORT)

client_socket = socket.socket()
print('连接,', ADDR)
client_socket.connect(ADDR)
print("连接成功")

def do_register():
    username = input('请输入用户名: ')
    password = getpass('请输入密码：')
    password2 = getpass('请示再次输入密码：')
    if password != password2:
        print('用户名和密码不一致, 注册失败')
        return
    if not username or not password:
        print('用户或密码不能为空，注册失败')
        return
    # 注册的数据包
    msg = 'R\t%s\t%s' % (username, password)
    client_socket.send(msg.encode())
    data = client_socket.recv(1024)
    if data == b'T':
        print('注册成功')
    else:
        print('注册失败')


def do_login():
    username = input('请输入用户名: ')
    password = getpass('请输入密码：')
    if not username or not password:
        print('用户或密码不能为空，登录失败')
        return
    # 登录的数据包
    msg = 'L\t%s\t%s' % (username, password)
    client_socket.send(msg.encode())
    data = client_socket.recv(1024)
    if data == b'T':
        print('登录成功')
        login(username)  # 进入登录的二级界面
    else:
        print('登录失败')

def do_query():
    while True:
        word = input('请输入单词(空结束):')
        if word == '':
            break
        msg = 'Q\t' + word
        client_socket.send(msg.encode())
        data = client_socket.recv(2048).decode()
        if data[0] == 'F':
            print('单词不存在')
        else:
            _, tran = data.split('\t')
            print(tran)

def do_hist():
    msg = b'H'
    client_socket.send(msg)
    data = client_socket.recv(100 * 10).decode()
    if data[0] == 'F':
        print('失败')
        return
    infos = data.split('\t')[1]
    for hist in infos.split(';'):
        if hist == '':
            print('没有记录')
            return
        item = hist.split(',')
        print('%s\t%s\t%s' % tuple(item))

def login(username):  # 进入二级界面的循环
    while True:
        print('''
        ========== Query ============
         1. 查单词  2. 历史记录 3. 注销
        =============================
        ''')
        cmd = input('请输入选项:')
        if cmd == '1':
            do_query()
        elif cmd == '2':
            do_hist()
        elif cmd == '3':
            client_socket.send(b'E')
            return
        else:
            print('请输入正确的选项!')

# 定义主程序函数
def main():
    # 进入一级界面的循环
    while True:
        print('''
        ========== Command ==========
         1. 注册     2.登录     3.退出
        =============================
        ''')
        cmd = input('请输入选项: ')
        if cmd == '1':
            do_register()
        elif cmd == '2':
            do_login()
        elif cmd == '3':
            client_socket.close()  # 关闭套接字
            return   # 退出main函数结束
        else:
            print('请输入正确的选项')


if __name__ == '__main__':
    main()